//
// Created by 崔世强 on 2018/1/15.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import WCDBSwift
import SwiftyJSON

class GroupListDidSyncEventProcessor: EventProcessorProtocol {
    static let instance = GroupListDidSyncEventProcessor()
    
    private init() {
    }
    
    //    private let service = ContactService()
    private let groupService = GroupService()
    private let queue = DispatchQueue(label: "com.tst.db",qos:.background)
    
    func process(params: Dictionary<String, Any>?) throws {
        do {
            guard AppStatusManager.instance.userLoginStatus.0 && AppStatusManager.instance.userLoginStatus.1 != nil && AppStatusManager.instance.userLoginStatus.1 != 0 else {
                throw ProcessError.LoginStatusError
            }
            
            guard let pathForUserDB = AppStatusManager.instance.urlForUserDB?.path else {
                throw ProcessError.InvalidParamError
            }
            
            guard let groups = params?["groups"] as? [Dictionary<String, Any>] else {
                throw ProcessError.InvalidParamError
            }
            
            let df = DateFormatter()
            df.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let nowString = "\(df.string(from: Date()))"
            
            //            let db = try Connection(pathForUserDB)
            let db = Database(at: pathForUserDB)
            try db.run(transaction: { _ in
                try GroupDao.updateAllDeleted()
                for group in groups {
                    let groupId = group["groupId"] as! Int
                    let name = group["name"] as? String
                    let typeStr = group["type"] as? String
                    let noDisturb = group["noDisturb"] as? Int
                    let type = Int(typeStr ?? "0")
                    let groupType = GroupType(rawValue: type ?? 2) ?? GroupType.normal
                    if (try GroupDao.getGroup(groupId)) != nil {
                        //                        groupInDb.name = name
                        //                        groupInDb.groupType = groupType
                        //                        groupInDb.deleted = false
                        try GroupDao.updateNoDisturb(groupId, noDisturb: noDisturb ?? 0 != 0)
                        try GroupDao.updateDelete(groupId, deleted: false)
                    } else {
                        let groupToSave = Group()
                        groupToSave.groupId = groupId
                        groupToSave.name = name
                        groupToSave.groupType = groupType
                        groupToSave.deleted = false
                        groupToSave.noDisturb = noDisturb ?? 0 != 0
                        try db.insert(groupToSave, intoTable: Group.table)
                    }
//                    
//                    if groupType != GroupType.service_platform {
//                        if let session = try SessionDao.getSession(groupId,chatType:.group) {
//                            session.name = name
//                            session.seq = groupType == .official ? 1 : 99
//                            session.deleted = 0
//                            try db.update(table: Session.table, on: [Session.CodingKeys.name,Session.CodingKeys.seq,Session.CodingKeys.deleted], with: session,where: Session.CodingKeys.id == session.id)
//                        } else {
//                            let session = Session()
//                            session.sessionServerId = groupId
//                            session.name = name
//                            session.chatType = .group
//                            session.seq = groupType == .official ? 1 : 99
//                            session.createdDatetime = nowString
//                            session.updatedDatetime = nowString
//                            try SessionDao.save(session)
//                        }
//                    }
                }
            })
            
            for group in groups {
                let groupId = group["groupId"] as! Int
                try groupService.getGroupInfoFromRemote(groupId,queue:queue)
            }
            
            //sync message after group synced
            EventProcessorWrapper().process(eventName: "newMessageDidExist", params: nil)
            
        } catch {
            throw error
        }
    }
}
